<template>
    <div class="div-view-search">
        <el-row gutter="20" class="search">
            <el-col id="btn0" :span="2">
                <el-button type="danger" @click="handleDeleteBatch">批量删除</el-button>
            </el-col>
            <el-col id="btn1" :span="2">
                <el-button type="success" @click="handleApproveBatch">批量解决</el-button>
            </el-col>
            <el-col id="btn2" :span="2">
                <el-button type="warning" @click="handleRejectBatch">批量驳回</el-button>
            </el-col>
            <el-col :span="4">
                <el-select v-model="selectedType1" placeholder="选择状态" @change="handleFilterChange1"
                    class="filter-select">
                    <el-option label="全部状态" value=""></el-option>
                    <el-option label="待解决" value="待解决"></el-option>
                    <el-option label="已解决" value="已解决"></el-option>
                    <el-option label="已拒绝" value="已拒绝"></el-option>
                </el-select>
            </el-col>
            <el-col :offset="8" :span="4">
                <el-input v-model="searchName" placeholder="请输入记录ID" />
            </el-col>
            <el-col :span="2">
                <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-col>
        </el-row>
    </div>
    <div class="div-view">
        <!-- 表格 -->
        <div class="table">
            <el-table :data="sortedFeedbacks" :header-cell-style="{ backgroundColor: '#f0f0f0' }" style="width: 100%"
                @sort-change="handleSortChange" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column property='feedbackId' label="举报记录ID" />
                <el-table-column property="userId" label="举报人ID" />
                <el-table-column property="targetId" label="被举报对象ID" />
                <el-table-column property="feedbackType" label="举报类型" />
                <el-table-column property="reportReason" label="举报原因" />
                <el-table-column property="reportedAt" label="举报时间" sortable="custom" />
                <el-table-column property="handleStatus" label="举报状态" />
                <el-table-column property="handleRemarks" label="处理备注" />
                <!-- 操作按钮 -->
                <el-table-column width="280" label="操作">
                    <template #default="{ row }">
                        <!-- 查看举报内容 -->
                        <el-button type="info" @click="viewReportContent(row.feedbackId)" link>
                            查看举报内容
                        </el-button>
                        <!-- 删除 -->
                        <el-button type="danger" @click="handleDeleteApplication(row)"
                            :disabled="row.handleStatus !== '已拒绝'" link>
                            删除
                        </el-button>
                        <!-- 处理 -->
                        <el-button type="success" @click="handleDealApplication(row)"
                            :disabled="row.handleStatus !== '待解决'" link>
                            处理
                        </el-button>
                        <!-- 驳回 -->
                        <el-button type="warning" @click="handleRejectApplication(row)"
                            :disabled="row.handleStatus !== '已拒绝'" link>
                            驳回
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页 -->
        <div class="demo-pagination-block">
            <el-pagination v-model:currentPage="pageNum" v-model:pageSize="pageSize" :page-sizes="[5, 10, 15, 20]"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                style="display: flex; justify-content: flex-end; margin-top: 10px;" />
        </div>
    </div>
    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" title="报告详情" width="500">
        <el-form :model="reportDetails" label-width="120px">
            <el-form-item label="举报原因:">
                <span>{{ reportDetails.reportReason }}</span>
            </el-form-item>
            <el-form-item label="处理状态:">
                <span>{{ reportDetails.handleStatus }}</span>
            </el-form-item>
            <el-form-item label="举报时间:">
                <span>{{ reportDetails.reportedAt }}</span>
            </el-form-item>
            <el-form-item label="处理备注:">
                <el-input v-model="reportDetails.handleRemarks" type="textarea"></el-input>
            </el-form-item>
        </el-form>
        <div style="display: flex; justify-content: flex-end;">
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false" type="danger">关闭</el-button>
                <el-button type="primary"
                    @click="submitHandleRemarks(reportDetails.feedbackId, reportDetails.handleRemarks)">
                    提交备注</el-button>
            </span>
        </div>
    </el-dialog>

</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

interface ReportDetails {
    feedbackId: number;
    reportReason: string;
    handleStatus: string;
    reportedAt: string;
    handleRemarks: string;
}

const reportDetails = ref<ReportDetails>({} as ReportDetails);
const dialogVisible = ref(false);

const viewReportContent = async (feedbackId: number) => {
    try {
        // 注意这里的URL，我们将feedbackId作为查询参数传递
        const response = await axios.get(`http://localhost:8088/feedbacks/check?feedbackId=${feedbackId}`);
        reportDetails.value = response.data;
        dialogVisible.value = true;
    } catch (error) {
        console.error('获取报告内容失败:', error);
        ElMessage.error('获取报告内容失败');
    }
};
const submitHandleRemarks = async (feedbackId, handleRemarks) => {
    try {
        // 构建包含ID和新备注的请求体
        const requestBody = {
            feedbackId: feedbackId,
            handleRemarks: handleRemarks,
        };
        const response = await axios.put(
            "http://localhost:8088/feedbacks/update",
            requestBody
        );

        if (response.data) {
            ElMessage.success("备注提交成功");
            const report = tableData.value.find((item) => item.feedbackId === feedbackId);
            if (report) {
                report.handleRemarks = handleRemarks;
            }
        }
        return response.data;
    } catch (error) {
        console.error("提交备注失败:", error);
        ElMessage.error("提交备注失败");
        return null;
    }
};



// 定义分页数据
const pageNum = ref(1);
const pageSize = ref(5);
// 定义总数据量
const total = ref(4);
const searchName = ref('');
//定义数据数组
const tableData = ref([]);

// 定义选中的下拉框值
const selectedType1 = ref('');
// 获取数据的函数
const fetchData1 = async () => {
    try {
        const response = await axios.get('http://localhost:8088/feedbacks/filter1', {
            params: {
                handleStatus: selectedType1.value,
            },
        });
        tableData.value = response.data.feedbacks;
    } catch (error) {
        console.error('Error fetching data:', error);
    }
};

// 处理下拉框变化的函数
const handleFilterChange1 = () => {
    fetchData1();
};


const getData = async () => {
    try {
        const response = await axios.get('http://localhost:8088/feedbacks/getReports');
        tableData.value = response.data;
    } catch (error) {
        console.error('获取数据错误: ', error);
    }
};
// 当前页或每页数量改变时重新获取数据
const handleSizeChange = () => {
    getData();
};
const handleCurrentChange = () => {
    getData();
};

const handleSearch = async () => {
    try {
        const response = await axios.get('http://localhost:8088/feedbacks/getByName',
            { params: { userId: searchName.value } });
        tableData.value = response.data;
    } catch (error) {
        console.error('查找出错:', error);
    }
};

// 更新操作的函数
const updateFeedbacksStatus = async (feedbackId, handleStatus) => {
    try {
        // 构建包含ID和新状态的请求体
        const requestBody = {
            feedbackId,
            handleStatus,
        };

        const response = await axios.put(
            "http://localhost:8088/feedbacks/update",
            requestBody
        );

        if (response.data) {
            ElMessage.success("操作成功");
            // 同步更新表格中的数据状态
            const feedbacks = tableData.value.find((item) => item.feedbackId === feedbackId);
            if (feedbacks) {
                feedbacks.handleStatus = handleStatus;
            }
        }
        return response.data;
    } catch (error) {
        console.error("更新失败:", error);
        ElMessage.error("更新失败");
        return null;
    }
};

// 查看
const handleLookApplication = (row) => {
    console.log(row);
};
// 删除
const handleDeleteApplication = (row) => {
    console.log(row);
};
// 处理
const handleDealApplication = (row) => {
    updateFeedbacksStatus(row.feedbackId, '已解决');
};
// 驳回
const handleRejectApplication = (row) => {
    updateFeedbacksStatus(row.feedbackId, '已拒绝');
};



// 组件挂载后获取初始数据
onMounted(() => {
    getData();
});


// 当前排序的属性和顺序
const sortProp = ref('');
const sortOrder = ref(''); // 'ascending' 或 'descending'
const sortedFeedbacks = computed(() => {
    return tableData.value.slice().sort((a, b) => {
        if (sortProp.value === 'reportedAt') {
            const timeA = new Date(a.reportedAt).getTime();
            const timeB = new Date(b.reportedAt).getTime();
            return sortOrder.value === 'ascending' ? timeA - timeB : timeB - timeA;
        }
        return 0;
    });
});

// 处理排序变化的函数
const handleSortChange = (newSortInfo) => {
    sortProp.value = newSortInfo.prop;
    sortOrder.value = newSortInfo.order;
}; 

const handleSelectionChange = (val) => {
  selectedRows.value = val;
};

const selectedRows = ref([]);
const handleRejectBatch = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning("请选择要删除的帖子");
        return;
    }
    try {
        const RequestBody = selectedRows.value.map((row) => ({
            feedbackId: row.feedbackId,
            handleStatus: '已拒绝',  // 固定为暂停中，或者根据需要动态赋值
        }));
        const response = await axios.put(
            "http://localhost:8088/feedbacks/updateByBatch",
            RequestBody
        );
        if (response.data) {
            ElMessage.success("操作成功"); // 操作成功，给用户反馈
            // 同步更新表格中的数据状态
            getData();
        }
        else {
            ElMessage.error("操作失败"); // 操作失败，给用户反馈
        }
    }catch (error) {
        console.error("更新失败:", error);
        ElMessage.error("更新失败"); // 更新失败，给用户反馈
    }
};

const handleApproveBatch = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning("请选择要通过的帖子");
        return;
    }
    try {
        const RequestBody = selectedRows.value.map((row) => ({
            feedbackId: row.feedbackId,
            handleStatus: '已解决',  
        }));
        const response = await axios.put(
            "http://localhost:8088/feedbacks/updateByBatch",
            RequestBody
        );
        if (response.data) {
            ElMessage.success("操作成功"); // 操作成功，给用户反馈
            getData();
        }
    }catch (error) {
        console.error("更新失败:", error);
        ElMessage.error("更新失败"); // 更新失败，给用户反馈
    }
};

const handleDeleteBatch = async () => {
    console.log('彻底删除');
};
</script>

<style scoped>
.el-header {
    padding-left: 0px;
    padding-right: 0px;
}

.el-main {
    background-color: #F2F2F2;
}

.el-aside {
    background-color: #7162A7;
    width: auto;
}

.div-view {
    background-color: #fff;
    padding: 10px 10px;
    /* 内边距 */
    border-radius: 5px;
    /* 圆角 */
    margin-bottom: 10px;
    /* 下边距 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 阴影 */
}

.div-view-search {
    background-color: #fff;
    padding: 10px 10px;
    /* 内边距 */
    border-radius: 5px;
    /* 圆角 */
    margin-bottom: 10px;
    /* 下边距 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 阴影 */
}



.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}

/* 图标特定类，仅用于图标 */
.status-icon-green {
    color: green;
    margin-right: 5px;
    /* 图标和文本之间的间距 */
}

.status-icon-red {
    color: red;
    margin-right: 5px;
}

.status-icon-gray {
    margin-right: 5px;
    color: gray;
}
</style>